/*****************************************************************
*
*	Netcare Agent Project
*		Copyright(C) 2010, Wicresoft EKA. All Rights Reserved.
*
*	Authors:
*		Miles Chen (milesch@wicresoft.com)
*		TingRong Shi (trshi@wicresoft.com)
*
*	Part of the product code depends on gSOAP under GPL license
*		Copyright(C) 2000-2010, Robert van Engelen, Genivia Inc. All Rights Reserved.
*
*****************************************************************/
#include <iostream>
#include <locale>

#include "TextWriterLogListener.h"
#include "DateTime.h"
#include "misc.h"

ALCATEL_SMS;

USING_STD;

#ifdef WIN32
	CTextWriterLogListener::CTextWriterLogListener(const wchar_t* logFile)
#else
	CTextWriterLogListener::CTextWriterLogListener(const char* logFile)
#endif
{
	//wcout << logFile << endl;

	_os.open(logFile, ios::in);
	if(_os.is_open())
	{
		// This means the log file exists
		_os.close();
		_os.open(logFile, ios::out | ios::app);
	}
	else
	{
		// Write BOM 0xEF,0xBB,0xBF
		// http://en.wikipedia.org/wiki/Byte_order_mark
		_os.open(logFile, ios::out);
#ifdef WIN32
		// Only write BOM in Windows
		_os.put(0xEF);
		_os.put(0xBB);
		_os.put(0xBF);
		_os.flush();
#endif
	}
}


CTextWriterLogListener::~CTextWriterLogListener(void)
{
	if(_os.is_open())
	{
		_os.close();
	}
}

void CTextWriterLogListener::WriteLine(const char* level, const wchar_t* message)
{
	char* p = _UTF8(message);
	WriteLine(level, p);
	delete[] p;
}

void CTextWriterLogListener::WriteLine(const char* level, const char* message)
{
	CDateTime* time = CDateTime::Now();
	_buffer << "[" << time->ToString() << "][" << level << "] " << message << endl;
	delete time;

	_os << _buffer.str();
	_os.flush();
	_buffer.str("");
}

ENDNS ENDNS